from django.shortcuts import render
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from .models import Area
from .serializers import AreaSerializer, SubAreaSerializer

# Create your views here.


# CacheResponseMixin 为省市区视图添加缓存
class AreasViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
    """
    省市区数据查询
    """
    pagination_class = None  # 区划信息不分页,禁用分页,因为后面的商品分页是全局的

    def get_queryset(self):
        """
        提供数据集
        """
        if self.action == 'list':
            return Area.objects.filter(parent=None)  # 只查省
            # return Area.objects.all()
        else:
            return Area.objects.all()

    def get_serializer_class(self):
        """
        提供序列化器
        """
        if self.action == 'list':
            return AreaSerializer  # 列表视图时要用的序列化器
        else:
            return SubAreaSerializer  # 详情视图时要用的序列化器